//
//  ChipChangeViewController.m
//  CarPark
//
//  Created by oceans on 2019/8/19.
//  Copyright © 2019 oceans. All rights reserved.
//

#import "ChipChangeViewController.h"
#import "ChipInstallCollectionViewCell.h"
#import <AipOcrSdk/AipOcrSdk.h>

@interface ChipChangeViewController () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, ChipInstallCellDelegate>

@property (strong, nonatomic) UICollectionView *collection;
@property (strong, nonatomic) UIButton *finish;
@property (copy, nonatomic) NSString *carStr;
@property (copy, nonatomic) NSString *chipStr;
@property (copy, nonatomic) NSString *xinChipStr;
@end

@implementation ChipChangeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[AipOcrService shardService] authWithAK:AK andSK:SK];
    [self setupView];
}

- (void)setupView {
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.title = @"安装芯片";
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, XNavigationHeight, ScreenWidth, ScreenHeight-XNavigationHeight-XBotSafeSpace-40.0) collectionViewLayout:layout];
    _collection.delegate = self;
    _collection.dataSource = self;
    _collection.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_collection];
    [_collection registerNib:[UINib nibWithNibName:@"ChipInstallCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"ChipInstallCollectionViewCell"];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.titleLabel.font = [UIFont systemFontOfSize:15.0];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setTitle:@"绑定上传" forState:UIControlStateNormal];
    button.frame = CGRectMake(0, ScreenHeight-XBotSafeSpace-40.0, ScreenWidth, 40.0+XBotSafeSpace);
    [button addTarget:self action:@selector(start) forControlEvents:UIControlEventTouchUpInside];
    button.backgroundColor = COLOR(242, 242, 242, 1);
    [self.view addSubview:button];
    self.finish = button;
    button.enabled = NO;
    
}

- (void)start {
    
    UIAlertController *con = [UIAlertController alertControllerWithTitle:@"确认信息" message:[NSString stringWithFormat:@"请您确认芯片信息并确认芯片已安装通电\n车架号：%@\n老芯片号：%@\n新芯片号：%@", _carStr, _chipStr, _xinChipStr] preferredStyle:UIAlertControllerStyleAlert];
    defweakself
    [con addAction:[UIAlertAction actionWithTitle:@"返回修改" style:UIAlertActionStyleCancel handler:nil]];
    [con addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself upload];
    }]];
    
    [self presentViewController:con animated:YES completion:nil];
}

- (void)upload {
    
    defweakself
    [HttpRequest postURL:kchip_change paras:@{@"vin_no": _carStr, @"old_rfid_id": _chipStr, @"new_rfid_id": _xinChipStr, @"task_id": [NSString stringWithFormat:@"%@", _info[@"id"]]} showProgress:YES successful:^(id  _Nullable result) {
        NSLog(@"%@", result);
    } failed:^(int code, NSString * _Nullable errMsg) {
        NSLog(@"%@", errMsg);
//        ChipInstallResultViewController *con = [[ChipInstallResultViewController alloc] init];
//        con.success = NO;
//        con.string = errMsg;
//        [weakself.navigationController pushViewController:con animated:YES];
    }];
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    
    return 0.0;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return CGSizeMake(ScreenWidth, 50.0);
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return 4;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ChipInstallCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ChipInstallCollectionViewCell" forIndexPath:indexPath];
    cell.tag = indexPath.item;
    cell.delegate = self;
    if (indexPath.item == 0) {
        cell.leftLabel.text = @"1";
        cell.rightButton.hidden = NO;
        cell.textField.placeholder = @"请拍照扫描车架号";
        cell.textField.text = _carStr;
        cell.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    }else if (indexPath.item == 1) {
        cell.leftLabel.text = @"2";
        cell.rightButton.hidden = NO;
        cell.textField.placeholder = @"请拍照扫描被更换芯片号";
        cell.textField.text = _chipStr;
        cell.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    }else if (indexPath.item == 2) {
        cell.leftLabel.text = @"3";
        cell.rightButton.hidden = NO;
        cell.textField.placeholder = @"请拍照扫描新芯片号";
        cell.textField.text = _chipStr;
        cell.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    }else if (indexPath.item == 3) {
        cell.leftLabel.text = @"3";
        cell.rightButton.hidden = YES;
        cell.textField.text = @"请将芯片安装完成并通电";
        cell.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    }
    return cell;
}

- (void)cellPressed:(NSInteger)tag {
    
    defweakself
    if (tag == 0) {
        UIViewController *con = [AipGeneralVC ViewControllerWithHandler:^(UIImage *image) {
            
            [[AipOcrService shardService] detectTextBasicFromImage:image withOptions:nil successHandler:^(id result) {
                NSLog(@"%@", result);
                if ([(NSArray *)result[@"words_result"] count] > 0) {
                    weakself.carStr = result[@"words_result"][0][@"words"];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakself check];
                    [weakself dismissViewControllerAnimated:YES completion:nil];
                });
            } failHandler:^(NSError *err) {
                NSLog(@"%@", err);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakself dismissViewControllerAnimated:YES completion:nil];
                });
            }];
        }];
        con.modalPresentationStyle = 0;
        [self presentViewController:con animated:YES completion:nil];
    }else if (tag == 1) {
        UIViewController *con = [AipGeneralVC ViewControllerWithHandler:^(UIImage *image) {
            
            [[AipOcrService shardService] detectTextBasicFromImage:image withOptions:nil successHandler:^(id result) {
                NSLog(@"%@", result);
                if ([(NSArray *)result[@"words_result"] count] > 0) {
                    weakself.chipStr = result[@"words_result"][0][@"words"];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakself check];
                    [weakself dismissViewControllerAnimated:YES completion:nil];
                });
            } failHandler:^(NSError *err) {
                NSLog(@"%@", err);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakself dismissViewControllerAnimated:YES completion:nil];
                });
            }];
        }];
        con.modalPresentationStyle = 0;
        [self presentViewController:con animated:YES completion:nil];
    }else {
        UIViewController *con = [AipGeneralVC ViewControllerWithHandler:^(UIImage *image) {
            
            [[AipOcrService shardService] detectTextBasicFromImage:image withOptions:nil successHandler:^(id result) {
                NSLog(@"%@", result);
                if ([(NSArray *)result[@"words_result"] count] > 0) {
                    weakself.xinChipStr = result[@"words_result"][0][@"words"];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakself check];
                    [weakself dismissViewControllerAnimated:YES completion:nil];
                });
            } failHandler:^(NSError *err) {
                NSLog(@"%@", err);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakself dismissViewControllerAnimated:YES completion:nil];
                });
            }];
        }];
        con.modalPresentationStyle = 0;
        [self presentViewController:con animated:YES completion:nil];
    }
}

- (void)check {
    
    defweakself
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakself.collection reloadData];
        if (weakself.carStr && weakself.chipStr) {
            
            weakself.finish.backgroundColor = COLOR(101, 101, 101, 1);
            weakself.finish.enabled = YES;
        }else {
            
            weakself.finish.backgroundColor = COLOR(242, 242, 242, 1);
            weakself.finish.enabled = NO;
        }
    });
}

@end
